//直接在里面，默认页面一打开就会执行
//获取标签
let ipt_account = document.getElementById("ipt_account");
let ipt_password = document.getElementById("ipt_password");
let cb_rem = document.getElementById("cb_rem");

//页面一打开就从localStorage中去寻找登录有关的数组
let users = JSON.parse(localStorage.getItem("users"));// | [];
console.log(users);

//记住密码的第二步
let rem_user = localStorage.getItem("rem_user");
// rem_user = rem_user ? JSON.parse(rem_user) : null;
if(rem_user) {
	rem_user = JSON.parse(rem_user);
	ipt_account.value = rem_user.account;
	ipt_password.value = rem_user.password;
	cb_rem.checked = true;
}

/**
 * 登录方法
 */
function login() {
	//1.获取输入框中的内容
	let account = ipt_account.value;
	let password = ipt_password.value;
	let rem = cb_rem.checked;
	console.log(account, password, rem);
	//数据较验
	//账号不能为空
	if(account.trim().length === 0) {
		alert("请输入账号");
		return;
	}
	
	if(password.trim().length < 6) {
		alert("密码至少要求6位");
		return;
	}
	
	//较验通过
	let result = false;
	//判断登录结果
	for(let index in users) {
		let item = users[index];
		if(item === null) {
			continue;
		}
		if(item.account === account && item.password === password) {
			result = true;
			break;
		}
	}
	
	if(result) {
		//登录成功
		//是否需要记住密码
		/*
			记住密码功能
				1.保存到localStorage中
				2.在页面一加载的时候就去localStorage中去读取，如果有就显示在对应的输入框中
		*/
		if(rem) {
			let rem_user = {
				account: account,
				password: password
			}
			//localStorage.setItem(key, value);key可以随意，但必须是字符串
			localStorage.setItem("rem_user", JSON.stringify(rem_user));
		}else {
			localStorage.setItem("rem_user", null);
		}
		
		//将用户账号存到sessionStorage中
		sessionStorage.setItem("account", account);
		//页面跳转
		location.href = "index.html";
	}else {
		//登录失败
		alert("账号或密码错误");
	}
}

function toReg() {
	location.href = "reg.html";
}